package com.mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.entity.MmallCategory;
import com.mall.entity.vo.CategoryVo;
import com.mall.service.MmallCategoryService;
import com.mall.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ppmall
 * @since 2021-09-19
 */
@CrossOrigin
@RestController
@RequestMapping("/mall/category")
public class MmallCategoryController {
    @Autowired
    private MmallCategoryService categoryService;

    @GetMapping(value = "/categorys")
    public R getAllCategoryList(HttpSession session) {
        List<MmallCategory> list = categoryService.list(null);
        return R.ok().data("categorys", list);
    }

    /**
     * 小程序接口(获取品类)
     * @param parentId
     * @return
     */
    @GetMapping(value = "/subCategory")
    public R getCategory(@RequestParam(value = "parentId", defaultValue = "0") int parentId) {
        QueryWrapper<MmallCategory> wrapper = new QueryWrapper();
        wrapper.eq("parent_id", parentId);
        List<MmallCategory> subCategorys = categoryService.list(wrapper);
        return R.ok().data("subCategorys", subCategorys);
    }

    @GetMapping(value = "/category")
    public R getCategoryById(@RequestParam(value = "id", defaultValue = "0") int id) {
        MmallCategory category = categoryService.getById(id);
        return R.ok().data("category", category);
    }

    @PostMapping(value = "/category")
    public R saveCategory(@RequestBody MmallCategory category) {
        boolean save = categoryService.saveCategory(category);
        return save ? R.ok() : R.error();
    }

    @PutMapping(value = "/category")
    public R updateCategory(@RequestBody MmallCategory category) {
        boolean update = categoryService.updateCategory(category);
        return update ? R.ok() : R.error();
    }

    @DeleteMapping(value = "/category/{id}")
    public R deleteCategory(@PathVariable("id") int id) {
        boolean delete = categoryService.deleteCategory(id);
        return delete ? R.ok() : R.error().message("删除失败 该分类不存在或分类下存在子类");
    }

    @GetMapping("categoryNestedListWithProduct")
    public R getCategoryNestedListWithProduct() {
        List<CategoryVo> categoryNestedList = categoryService.getCategoryNestedList(true);
        return R.ok().data("categoryNestedList", categoryNestedList);
    }

    @GetMapping("categoryNestedList")
    public R getCategoryNestedList() {
        List<CategoryVo> categoryNestedList = categoryService.getCategoryNestedList(false);
        return R.ok().data("categoryNestedList", categoryNestedList);
    }

}

